import os
import argparse
from datetime import datetime

def is_valid_date_prefix(file_name):
    """检查文件名是否以有效的日期前缀开头（YYMMDD）"""
    try:
        prefix = file_name.split('.')[0]
        datetime.strptime(prefix, '%y%m%d')
        return True
    except ValueError:
        return False

def get_files_creation_dates_and_rename(folder_path):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        
        # 只处理文件，忽略子文件夹
        if os.path.isfile(file_path):
            stats = os.stat(file_path)
            creation_time = stats.st_birthtime
            creation_date = datetime.fromtimestamp(creation_time).strftime('%y%m%d')
            
            # 检查文件名是否已经有正确的日期前缀
            if not file_name.startswith(creation_date) or not is_valid_date_prefix(file_name):
                # 提取不带日期前缀的原始文件名
                original_file_name = file_name.split('.', 1)[-1] if is_valid_date_prefix(file_name) else file_name
                new_file_name = f"{creation_date}.{original_file_name}"
                new_file_path = os.path.join(folder_path, new_file_name)
                os.rename(file_path, new_file_path)
                print(f"Renamed {file_path} to {new_file_path}")

def main():
    parser = argparse.ArgumentParser(description='Rename files by adding their creation dates.')
    parser.add_argument('folder_path', type=str, help='The path to the folder')
    args = parser.parse_args()
    
    folder_path = args.folder_path
    get_files_creation_dates_and_rename(folder_path)

if __name__ == '__main__':
    main()
